import Vue from 'vue'
import VueRouter from 'vue-router'
//引入局部组件
import Login from '../components/Login'
import Home from '../components/Home.vue'
import Welcome from '../components/Welcome'
import Users from '../components/Users/Users.vue'
import Rights from '../components/Power/Rights.vue'
import Roles from '../components/Power/Roles.vue'


Vue.use(VueRouter)

const routes = [
  //分发路由
  {
    path: '/login',
    component: Login
  },
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: Users
      },
      {
        path: '/rights',
        component: Rights
      },
      {
        path: '/roles',
        component: Roles
      }
    ]
  },

]

const router = new VueRouter({
  routes
})

// const router = new VueRouter({})
//注册全局前置守卫
router.beforeEach((to, from, next) => {
  //to 即将进入的目标 路由对象
  //from 当前导航正要离开的路由
  //next 是否放行
  // console.log(to);
  // 1 如果是login登录页直接放行
  if (to.path == '/login') {
    return next()
  }
  // 2 判断token是否为空
  const token = localStorage.getItem('token')
  if (!token) {
    return next('/login')
  }
  next()
})
export default router
